<?php
/**
 * 用户批量导入
 * author itholiday@126.com
 */
global $_W, $_GPC;
load()->func('tpl');
$html_title = $_W['current_module']['title'];
$op = !empty($_GPC['op']) ? $_GPC['op'] : 'list';
//上传表格
if ($op == 'upload') {
    if (!is_post()) {
        ajaxError('没有权限');
    }
    $file = $_FILES["file"];
    if (!$file) {
        ajaxError('请上传文件');
    }
    $allowedExts = array("xlsx", 'vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel');
    $temp = explode("/", $file["type"]);
    $extension = end($temp);

    if (!in_array($extension, $allowedExts)) {
        ajaxError('只能上传表格文件');
    }
    if ($file["size"] > 4 * 1024 * 1024) {
        ajaxError('文件大小超过4M');
    }
    $file_dir = '../attachment/userimport/' . date('Ymd');//web文件夹的上层即为根目录
    if (!file_exists($file_dir)) {
        mkdirs($file_dir, '757');
    }
    $filename = $file_dir . '/' . date('Y年_m月_d日_H时_i分_s秒') . '.xlsx';
    $res = move_uploaded_file($file["tmp_name"], $filename);
    if (!$res) {
        @unlink($filename);
        ajaxError('上传失败，稍后重试');
    }
    ajaxSuccess('上传成功', substr($filename, 14));
}

//导出模板
if ($op == 'default') {
    $fileName = '会员列表_' . date('YmdHis');
    $header = array(
        '手机号', '身份证号', '支付宝姓名', '支付宝账号'
    );

    exportExcel([], $fileName, $header, '会员信息');
}

if ($op == 'import1') {
    if (is_post()) {
        error_reporting(E_ERROR);
        ini_set('display_errors',0);
        $request = $_GPC;
        $file_name = $request['targetfile'];

        $savePath = "../attachment/userimport" . DS . date('Ymd') . DS;
        if (!file_exists($savePath . $file_name)) {
            echo json_encode(['code' => 0, 'msg' => '该文件不存在']);
            exit;
        }
        $file_types = explode('.', $file_name);
        $file_type = $file_types[1];
        /*
        *对上传的Excel数据进行处理生成编程数据,这个函数会在下面第三步的ExcelToArray类中
        *注意：这里调用执行了第三步类里面的read函数，把Excel转化为数组并返回给$res,再进行数据库写入
        */
        $file = IA_ROOT . '/addons/' . ModuleName() . '/api/phpexcel/Classes/PHPExcel.php';
        if (is_file($file)) {
            require_once $file;
        } else {
            return false;
        }
        require IA_ROOT . '/addons/' . ModuleName() . '/api/phpexcel/Classes/ExcelToArray.php';//导入excelToArray类
        //引入这个类试了百度出来的好几个方法都不行。最后简单粗暴的使用了require方式。这个类想放在哪里放在哪里。只要路径对就行。

        $ExcelToArrary = new ExcelToArrary();//实例化

        $res = $ExcelToArrary->read($savePath . $file_name, "UTF-8", $file_type);//传参,判断office2007还是office2003

        /*对生成的数组进行数据库的写入*/
        $data = array();//要插入的二维数组数据
        //第一行是表头，从第二行开始
        $password = cmf_password('123456');
        $vip_end_time = strtotime("+1 year");

        $data = array();
        if (!$res || count($res) < 2) {
            echo json_encode(['code' => 0, 'msg' => '不存在有效数据，请重新上传选择']);
            exit;
        }
        $now_time = time();
        $import_batch = 'BT' . date('YmdHis');
        foreach ($res as $k => $v) {
            if ($k > 1) {
                $res = pdo_get('yq_haircircle_users', array('mobile' => $v[1]));
                $tmp['mobile'] = $v[1];
                if ($res || in_array($tmp, $data)) continue;//去重
                //固定数据
                $data[$k]['user_pass'] = $password;
                $data[$k]['user_status'] = 1;
                $data[$k]['vip_end_time'] = $vip_end_time;
                $data[$k]['import_batch'] = $import_batch;
                $data[$k]['create_time'] = $now_time;
                //表格数据
                $data[$k]['mobile'] = $v[1];
                $data[$k]['idno'] = $v[2];
                $data[$k]['alipay_name'] = $v[3];
                $data[$k]['alipay_account'] = $v[4];
            }
        }

        if (!$data) {
            echo json_encode(['code' => 0, 'msg' => '该文档中用户已存在，导入失败']);
            exit;
        }
        //插入的操作最好放在循环外
        $result = pdo_insert_all('yq_haircircle_users',$data);
        if (!empty($result)) {
            @unlink($savePath . $file_name);
            //更新
            $tuiguang_setting = cmf_get_option('tuiguang_setting');
            if(isset($tuiguang_setting['thumb1']) && !empty($tuiguang_setting['thumb1'])){
                $bg = '../attachment/' . cmf_asset_relative_url($tuiguang_setting['thumb1']);
            }else{
                $bg = '../addons/yq_haircircle/qrcode-background.png';
            }
            foreach ($data as $k => $v) {
                $data[$k]['id'] = pdo_getcolumn('yq_haircircle_users', array('mobile' => $v['mobile']), 'id');
                $data[$k]['user_login'] = $data[$k]['id'];
                $url = 'http://' . $_SERVER['HTTP_HOST'] . '/app/' . $this->createMobileUrl('public', array('op' => 'register', 'pid' => $data[$k]['id']));
                $qrcode = cmf_get_qrcode($url,251,$bg);
                $data[$k]['qrcode'] = $qrcode ? $qrcode : '';
            }

            $res = pdo_update_all('yq_haircircle_users',$data);
            $count = count($data);

            if (!empty($result) && empty($res)) {
                echo json_encode(['code' => 0, 'msg' => '导入成功' . $count . '条数据，更新user_login失败']);
                exit;
            }
            echo json_encode(['code' => 1, 'msg' => '成功导入' . $count . '条数据']);
            exit;
        } else {
            echo json_encode(['code' => 0, 'msg' => '导入失败']);
            exit;
        }
    }
}

if ($op == 'list') {
//查找所有文件
    $filepath = '../attachment/userimport/' . date('Ymd');
    !is_file($filepath) && mkdirs($filepath);
    $list = scandir($filepath, 1);
    $list = array_merge(array_diff($list, array('.', '..')));
    $list = $list ? $list : [];
    include $this->template('web/member_import');
}

